//
//  OrderConfirmationView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI


struct OrderConfirmationView: View {
    @EnvironmentObject var dataManager: DataManager
    let order: Order
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: 24) {
                    successHeader
                    orderDetailsCard
                    tipsSection
                    Spacer(minLength: 20)
                }
                .padding()
            }
            .navigationTitle(dataManager.currentLanguage == "zh" ? "订单确认" : "Order Confirmation")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                Button {
                    dismiss()
                } label: {
                    Text(dataManager.currentLanguage == "zh" ? "完成" : "Done")
                        .fontWeight(.semibold)
                }
            }
            }
        }
    }
    
    private var successHeader: some View {
        VStack(spacing: 16) {
            Image(systemName: "checkmark.circle.fill")
                .font(.system(size: 80))
                .foregroundColor(.green)
            
            Text(dataManager.currentLanguage == "zh" ? "订单提交成功！" : "Order Submitted Successfully!")
                .font(.title2)
                .fontWeight(.bold)
            
            Text(dataManager.currentLanguage == "zh" ? "您的美食正在精心制作中" : "Your delicious meal is being prepared")
                .font(.subheadline)
                .foregroundColor(.secondary)
        }
        .padding(.top, 40)
    }
    
    private var orderDetailsCard: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "订单详情" : "Order Details")
                    .font(.headline)
                    .fontWeight(.semibold)
                Spacer()
            }
            
            Divider()
            
            orderNumberRow
            diningTypeRow
            if order.diningType == .dineIn, let tableNumber = order.tableNumber {
                tableNumberRow(tableNumber: tableNumber)
            }
            estimatedTimeRow
            
            Divider()
            
            orderItemsSection
            
            Divider()
            
            priceDetailsSection
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(12)
    }
    
    private var orderNumberRow: some View {
        HStack {
            Text(dataManager.currentLanguage == "zh" ? "订单号" : "Order Number")
                .foregroundColor(.secondary)
            Spacer()
            Text("#\(order.id.uuidString.prefix(8))")
                .fontWeight(.medium)
        }
    }
    
    private var diningTypeRow: some View {
        HStack {
            Text(dataManager.currentLanguage == "zh" ? "用餐方式" : "Dining Type")
                .foregroundColor(.secondary)
            Spacer()
            Text(order.displayOrderType(language: dataManager.currentLanguage))
                .fontWeight(.medium)
        }
    }
    
    private func tableNumberRow(tableNumber: String) -> some View {
        HStack {
            Text(dataManager.currentLanguage == "zh" ? "桌号" : "Table Number")
                .foregroundColor(.secondary)
            Spacer()
            Text(tableNumber)
                .fontWeight(.medium)
        }
    }
    
    private var estimatedTimeRow: some View {
        HStack {
            Text(dataManager.currentLanguage == "zh" ? "预计完成时间" : "Estimated Time")
                .foregroundColor(.secondary)
            Spacer()
            Text("15-20 " + (dataManager.currentLanguage == "zh" ? "分钟" : "minutes"))
                .fontWeight(.medium)
                .foregroundColor(.orange)
        }
    }
    
    private var orderItemsSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text(dataManager.currentLanguage == "zh" ? "订购项目" : "Order Items")
                .font(.subheadline)
                .weighted(.semibold)
            
            ForEach(order.items, id: \.id) { item in
                HStack(alignment: .top) {
                    VStack(alignment: .leading, spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? item.menuItem.name : item.menuItem.englishName)
                            .font(.subheadline)
                            .fontWeight(.medium)
                        
                        if let meatType = item.selectedMeatType {
                            Text(dataManager.currentLanguage == "zh" ? meatType.chineseName : meatType.englishName)
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                        
                        if !item.specialInstructions.isEmpty {
                            Text(dataManager.currentLanguage == "zh" ? "备注: " : "Note: " + item.specialInstructions)
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                    }
                    
                    Spacer()
                    
                    VStack(alignment: .trailing) {
                        Text("×\(item.quantity)")
                            .font(.subheadline)
                            .foregroundColor(.secondary)
                        Text("S$\(String(format: "%.2f", item.totalPrice))")
                            .font(.subheadline)
                            .fontWeight(.medium)
                    }
                }
            }
        }
    }
    
    private var priceDetailsSection: some View {
        VStack(spacing: 8) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "小计" : "Subtotal")
                    .foregroundColor(.secondary)
                Spacer()
                Text("S$\(String(format: "%.2f", order.subtotal))")
            }
            
            if order.discount > 0 {
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "优惠" : "Discount")
                        .foregroundColor(.secondary)
                    Spacer()
                    Text("-S$\(String(format: "%.2f", order.discount))")
                        .foregroundColor(.green)
                }
            }
            
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "税费" : "Tax")
                    .foregroundColor(.secondary)
                Spacer()
                Text("S$\(String(format: "%.2f", order.tax))")
            }
            
            Divider()
            
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "总计" : "Total")
                    .font(.headline)
                    .fontWeight(.bold)
                Spacer()
                Text("S$\(String(format: "%.2f", order.total))")
                    .font(.headline)
                    .fontWeight(.bold)
                    .foregroundColor(.orange)
            }
        }
    }
    
    private var tipsSection: some View {
        VStack(spacing: 12) {
            HStack {
                Image(systemName: "bell.fill")
                    .foregroundColor(.orange)
                Text(dataManager.currentLanguage == "zh" ? 
                     "我们会在您的美食准备好时通知您" :
                     "We'll notify you when your food is ready")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
            
            if order.diningType == .dineIn {
                HStack {
                    Image(systemName: "location.fill")
                        .foregroundColor(.blue)
                    Text(dataManager.currentLanguage == "zh" ? 
                         "请在您的座位等候，我们会为您送餐" :
                         "Please wait at your table, we'll bring your order")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
            } else {
                HStack {
                    Image(systemName: "bag.fill")
                        .foregroundColor(.green)
                    Text(dataManager.currentLanguage == "zh" ? 
                         "请在收到通知后前往前台取餐" :
                         "Please come to the counter when notified")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(12)
        .overlay(
            RoundedRectangle(cornerRadius: 12)
                .stroke(Color(.systemGray4), lineWidth: 1)
        )
    }
}

#Preview {
    let dataManager = DataManager.shared
    let sampleOrder = Order(
        userId: nil,
        tableNumber: "A05",
        items: [
            CartItem(
                menuItem: MenuItem(
                    name: "招牌韩式炸鸡",
                    englishName: "Signature Korean Fried Chicken",
                    description: "酥脆外皮，嫩滑鸡肉",
                    englishDescription: "Crispy coating, tender chicken",
                    price: 18.90,
                    category: .recommended,
                    imageName: "korean_chicken"
                ),
                quantity: 2,
                selectedMeatType: .chicken,
                specialInstructions: "少辣"
            )
        ],
        diningType: .dineIn,
        paymentMethod: .creditCard,
        specialInstructions: "请快一点"
    )
    
    OrderConfirmationView(order: sampleOrder)
        .environmentObject(dataManager)
}